<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>JavaMail📪邮件接发技术 | 小李博客</title><meta name="keywords" content="企业常用技术"><meta name="author" content="小李博客"><meta name="copyright" content="小李博客"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="电子邮件的接发过程感谢YSOcean||Java发邮件  假设用户A从QQ邮箱发送邮件到用户B163邮箱的图示，然后对图示的过程进行详细的介绍：  用户A的电子邮箱为：&amp;#x78;&amp;#x78;&amp;#x40;&amp;#x71;&amp;#113;&amp;#x2e;&amp;#x63;&amp;#x6f;&amp;#x6d;，通过邮件客户端软件写好一封邮件，交到QQ的邮件服务器，这一步使用的协议是SMTP,对应图示的①； QQ邮箱会根据用户A发送">
<meta property="og:type" content="article">
<meta property="og:title" content="JavaMail📪邮件接发技术">
<meta property="og:url" content="http://xiaoliblog.cn/page/JavaMail.html">
<meta property="og:site_name" content="小李博客">
<meta property="og:description" content="电子邮件的接发过程感谢YSOcean||Java发邮件  假设用户A从QQ邮箱发送邮件到用户B163邮箱的图示，然后对图示的过程进行详细的介绍：  用户A的电子邮箱为：&amp;#x78;&amp;#x78;&amp;#x40;&amp;#x71;&amp;#113;&amp;#x2e;&amp;#x63;&amp;#x6f;&amp;#x6d;，通过邮件客户端软件写好一封邮件，交到QQ的邮件服务器，这一步使用的协议是SMTP,对应图示的①； QQ邮箱会根据用户A发送">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://cdn.jsdelivr.net/gh/xiaoliblog/image@49db1e1882ba97dcb3a0c2be5a580006f80f1f4f/2021/01/24/7309dc108232cf99fd79b144f350f4f5.png">
<meta property="article:published_time" content="2020-12-31T07:59:00.510Z">
<meta property="article:modified_time" content="2021-04-27T13:05:26.204Z">
<meta property="article:author" content="小李博客">
<meta property="article:tag" content="企业常用技术">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://cdn.jsdelivr.net/gh/xiaoliblog/image@49db1e1882ba97dcb3a0c2be5a580006f80f1f4f/2021/01/24/7309dc108232cf99fd79b144f350f4f5.png"><link rel="shortcut icon" href="https://cdn.jsdelivr.net/gh/xiaoliblog/image@6b5e7ef72be1c8973d94e5a9c49accbf775ad820/2021/02/01/c485da031fe0e464d04eaba8a66c4a8f.png"><link rel="canonical" href="http://xiaoliblog.cn/page/JavaMail"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/instantsearch.js@2.10.5/dist/instantsearch.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/instantsearch.js@2.10.5/dist/instantsearch.min.js" defer></script><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: {"appId":"RTG4CPNBLJ","apiKey":"f1745bdad68ceec57653b78244fe332c","indexName":"MyBlogIndex","hits":{"per_page":6},"languages":{"input_placeholder":"搜索文章","hits_empty":"找不到您查询的内容：${query}","hits_stats":"找到 ${hits} 条结果，用时 ${time} 毫秒"}},
  localSearch: undefined,
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":200},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: {"limitCount":100,"languages":{"author":"作者: 小李博客","link":"链接: ","source":"来源: 小李博客","info":"著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。"}},
  lightbox: 'mediumZoom',
  Snackbar: {"chs_to_cht":"你已切换为繁体","cht_to_chs":"你已切换为简体","day_to_night":"你已切换为深色模式","night_to_day":"你已切换为浅色模式","bgLight":"#49b1f5","bgDark":"#121212","position":"top-center"},
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isanchor: true
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = { 
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2021-04-27 21:05:26'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const fontSizeVal = saveToLocal.get('global-font-size')
    if (fontSizeVal !== undefined) {
      document.documentElement.style.setProperty('--global-font-size', fontSizeVal + 'px')
    }
    })(window)</script><link rel="stylesheet" href="/css/MyStyle/MyStyle.css" media="defer" onload="this.media='all'"/><link rel="stylesheet" href="/css/MyStyle/tagStyle.css" media="defer" onload="this.media='all'"/><link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/zykjofficial/zykjresource@master/css/font-awesome-animation.min.css" media="defer" onload="this.media='all'"/><link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/sviptzk/StaticFile_HEXO@latest/butterfly/css/font-awesome-animation.min.css" media="defer" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/sviptzk/StaticFile_HEXO@latest/butterfly/css/plugins.min.css" media="defer" onload="this.media='all'"><meta name="generator" content="Hexo 5.2.0"><link rel="alternate" href="/atom.xml" title="小李博客" type="application/atom+xml">
</head><body><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="author-avatar"><img class="avatar-img" src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@6b5e7ef72be1c8973d94e5a9c49accbf775ad820/2021/02/01/c485da031fe0e464d04eaba8a66c4a8f.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/archives/"><div class="headline">文章</div><div class="length-num">210</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/tags/"><div class="headline">标签</div><div class="length-num">38</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/categories/"><div class="headline">分类</div><div class="length-num">56</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/box/"><i class="fa-fw fa fa-briefcase"></i><span> 工具箱</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-book"></i><span> 找文章</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/categories/"><i class="fa-fw fa fa-folder-open"></i><span> 分类</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fa fa-address-card"></i><span> 关于</span></a></div><div class="menus_item"><a class="site-page" href="/messageboard/"><i class="fa-fw fa fa-paper-plane"></i><span> 留言</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="not-top-img" id="page-header"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">小李博客</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/box/"><i class="fa-fw fa fa-briefcase"></i><span> 工具箱</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-book"></i><span> 找文章</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/categories/"><i class="fa-fw fa fa-folder-open"></i><span> 分类</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fa fa-address-card"></i><span> 关于</span></a></div><div class="menus_item"><a class="site-page" href="/messageboard/"><i class="fa-fw fa fa-paper-plane"></i><span> 留言</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav></header><main class="layout" id="content-inner"><div id="post"><div id="post-info"><h1 class="post-title">JavaMail📪邮件接发技术</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2020-12-31T07:59:00.510Z" title="发表于 2020-12-31 15:59:00">2020-12-31</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2021-04-27T13:05:26.204Z" title="更新于 2021-04-27 21:05:26">2021-04-27</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E4%BC%81%E4%B8%9A%E5%B8%B8%E7%94%A8%E6%8A%80%E6%9C%AF/">企业常用技术</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E4%BC%81%E4%B8%9A%E5%B8%B8%E7%94%A8%E6%8A%80%E6%9C%AF/JavaMail%E9%82%AE%E4%BB%B6%E6%8A%80%E6%9C%AF/">JavaMail邮件技术</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">7.2k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>28分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="JavaMail📪邮件接发技术"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div><article class="post-content" id="article-container"><h1 id="电子邮件的接发过程"><a href="#电子邮件的接发过程" class="headerlink" title="电子邮件的接发过程"></a>电子邮件的接发过程</h1><div class="note success simple"><p>感谢<a target="_blank" rel="noopener" href="https://www.cnblogs.com/ysocean/p/7652934.html">YSOcean</a>||<a target="_blank" rel="noopener" href="https://www.runoob.com/java/java-sending-email.html">Java发邮件</a></p>
</div>
<p>假设<strong>用户A从QQ邮箱发送邮件到用户B163邮箱</strong>的图示，然后对图示的过程进行详细的介绍：<br><img src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/31/1b1ff5cb7ec90c03d9eb2753feb94056.png"></p>
<ol>
<li>用户A的电子邮箱为：<a href="mailto:&#x78;&#x78;&#x40;&#x71;&#113;&#x2e;&#x63;&#x6f;&#x6d;">&#x78;&#x78;&#x40;&#x71;&#113;&#x2e;&#x63;&#x6f;&#x6d;</a>，通过邮件客户端软件写好一封邮件，交到QQ的邮件服务器，这一步使用的协议是<code>SMTP</code>,对应图示的①；</li>
<li>QQ邮箱会根据用户A发送的邮件进行<strong>解析</strong>，也就是根据收件地址判断是否是自己管辖的账户，如果收件地址也是QQ邮箱，那么会直接存放到自己的存储空间。这里我们假设收件地址不是QQ邮箱，而是163邮箱，那么QQ邮箱就会将邮件转发到163邮箱服务器，转发使用的协议也是<code>SMTP</code>，对应图示的②；</li>
<li>163邮箱服务器接收到QQ邮箱转发过来的邮件，也会判断收件地址是否是自己，发现是自己的账户，那么就会将QQ邮箱转发过来的邮件存放到自己的内部存储空间，对应图示的③；</li>
<li>用户A将邮件发送了之后，就会通知用户B去指定的邮箱收取邮件。用户B会通过邮件客户端软件先向163邮箱<strong>服务器请求</strong>，要求收取自己的邮件，对应图示的④；</li>
<li>163邮箱服务器收到用户B的请求后，会从自己的存储空间中取出B未收取的邮件，对应图示⑤；</li>
<li>163邮箱服务器取出用户B未收取的邮件后，将邮件发给用户B，对应图示的⑥；最后三步用户B收取邮件的过程，使用的协议是<code>POP3</code>;</li>
</ol>
<h2 id="邮件服务器"><a href="#邮件服务器" class="headerlink" title="邮件服务器"></a>邮件服务器</h2><p>图示出现了两个邮件服务器，QQ和163邮件服务器。用户想要在网上收发邮件，必须要有专门的邮件服务器。邮件服务器我们可以假想为现实生活中的邮局。</p>
<ul>
<li>如果按<strong>功能</strong>划分，邮件服务器可以划分为两种类型：<ol>
<li><strong>SMTP邮件服务器</strong>：替用户<strong>发送邮件和接收</strong>外面发送给本地用户的邮件，对应上图的第一、二步。它相当于现实生活中邮局的邮件接收部门（可接收普通用户要投出的邮件和其他邮局投递进来的邮件）。</li>
<li><strong>POP3/IMAP邮件服务器</strong>：帮助用户<strong>读取SMTP邮件服务器接收进来的邮件</strong>，对应上图的第六步。它相当于专门为前来取包裹的用户提供服务的部门。</li>
</ol>
</li>
</ul>
<h2 id="电子邮箱"><a href="#电子邮箱" class="headerlink" title="电子邮箱"></a>电子邮箱</h2><ul>
<li>电子邮箱也称为E-mail地址，比如用户A的<a href="mailto:&#120;&#x78;&#64;&#113;&#x71;&#46;&#x63;&#x6f;&#x6d;">&#120;&#x78;&#64;&#113;&#x71;&#46;&#x63;&#x6f;&#x6d;</a>，和用户B的<a href="mailto:&#120;&#x78;&#x40;&#x31;&#54;&#51;&#x2e;&#x63;&#x6f;&#109;">&#120;&#x78;&#x40;&#x31;&#54;&#51;&#x2e;&#x63;&#x6f;&#109;</a>。</li>
<li>用户能<strong>通过E-mail地址标识自己发送的电子邮件</strong>，同时也可以通过这个地址接收别人发来的电子邮件</li>
<li>电子邮箱需要到邮件服务器进行申请，也就是说，电子邮箱其实就是用户在<strong>邮件服务器上申请的账户</strong>。邮件服务器会把接收到的邮件保存到为该账户所分配的邮箱空间中，用户通过用户名密码登录到邮件服务器查收该地址已经收到的邮件。一般来讲，邮件服务器为用户分配的邮箱空间是有限的。</li>
</ul>
<h2 id="邮件客户端软件"><a href="#邮件客户端软件" class="headerlink" title="邮件客户端软件"></a>邮件客户端软件</h2><p>我们可以直接在网站上进行邮件收发，也可以用邮件客户端软件。比如常见的FoxMail，Outlook Express。邮件客户端软件通常集邮件撰写，发送和收发功能于一体，主要用于<strong>帮助用户将邮件发送给SMTP邮件服务器和从POP3/IMAP邮件服务器读取用户的电子邮件</strong>。</p>
<div class="note success simple"><p>推荐使用<strong>163邮箱</strong>，不推荐使用QQ邮箱！</p>
</div>
<h2 id="邮件传输协议"><a href="#邮件传输协议" class="headerlink" title="邮件传输协议"></a>邮件传输协议</h2><p>电子邮件需要在邮件客户端和邮件服务器之间，以及两个邮件服务器之间进行邮件传递，那就必须要遵守一定的规则，这个规则就是邮件传输协议。下面我们分别简单介绍几种协议（后面会详细讲解）：</p>
<ol>
<li><strong>SMTP协议</strong>：全称为 <code>Simple Mail Transfer Protocol</code>，<strong>简单邮件传输协议</strong>。它定义了邮件客户端软件和SMTP邮件服务器之间，以及两台SMTP邮件服务器之间的通信规则。</li>
<li><strong>POP3协议</strong>：全称为 <code>Post Office Protocol</code>，<strong>邮局协议</strong>。它定义了邮件客户端软件和POP3邮件服务器的通信规则。</li>
<li><strong>IMAP协议</strong>：全称为<code> Internet Message Access Protocol</code>,<strong>Internet消息访问协议</strong>，它是对POP3协议的一种扩展，也是定义了邮件客户端软件和IMAP邮件服务器的通信规则。</li>
</ol>
<h1 id="JavaMail"><a href="#JavaMail" class="headerlink" title="JavaMail"></a>JavaMail</h1><p>实际项目中我们不需要考虑邮件的底层实现协议，因为 sun 公司（现在已经被orcal收购了）开发的JavaMail API 就是为方便Java开发人员在应用程序中实现邮件接收和发送功能而提供的一套标准开发包，屏蔽了底层的邮件实现协议</p>
<h2 id="JavaMail介绍"><a href="#JavaMail介绍" class="headerlink" title="JavaMail介绍"></a>JavaMail介绍</h2><ul>
<li><p>JavaMail 是sun公司（现以被甲骨文收购）为方便Java开发人员在应用程序中实现邮件发送和接收功能而提供的一套标准开发包，它支持一些常用的邮件协议，如前面所讲的SMTP，POP3，IMAP,还有MIME等。我们在使用JavaMail API 编写邮件时，无须考虑邮件的底层实现细节，只要调用JavaMail 开发包中相应的API类就可以了。</p>
</li>
<li><p>本项目开源代码：<a target="_blank" rel="noopener" href="https://github.com/xiaoliblog/MyCode/tree/main/JavaMailProject">https://github.com/xiaoliblog/MyCode/tree/main/JavaMailProject</a></p>
</li>
<li><p>JavaMail下载地址：<a target="_blank" rel="noopener" href="https://github.com/javaee/javamail/releases">https://github.com/javaee/javamail/releases</a>，下载<code>javax.mail.jar</code></p>
</li>
<li><p>Maven地址：<a target="_blank" rel="noopener" href="https://mvnrepository.com/artifact/javax.mail/mail">https://mvnrepository.com/artifact/javax.mail/mail</a> ，还需要下载一个用于支持的<code>activation.jar</code>包</p>
</li>
</ul>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- https://mvnrepository.com/artifact/javax.mail/mail --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>javax.mail<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>mail<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>1.4.7<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"><span class="comment">&lt;!-- https://mvnrepository.com/artifact/javax.activation/activation --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>javax.activation<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>activation<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>1.1.1<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h2 id="JavaMail-API"><a href="#JavaMail-API" class="headerlink" title="JavaMail API"></a>JavaMail API</h2><ul>
<li>JavaMail API 按照功能可以划分为如下三大类：<ol>
<li>创建和解析邮件的API</li>
<li>发送邮件的API</li>
<li>接收邮件的API</li>
</ol>
</li>
<li>以上三种类型的API在JavaMail 中由多个类组成，但是主要有四个核心类，我们在编写程序时，记住这四个核心类，就很容易编写出Java邮件处理程序</li>
</ul>
<p><img src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/31/df232bb78ce012a3ce18114c0d377fba.png"></p>
<ul>
<li><p><strong>Message 类</strong>:<code>javax.mail.Message</code> 类是<strong>创建和解析邮件</strong>的核心 API，这是一个抽象类，通常使用它的子类javax.mail.internet.MimeMessage 类。它的实例对象表示一份电子邮件。客户端程序发送邮件时，首先使用创建邮件的 JavaMail API 创建出封装了邮件数据的 Message 对象，然后把这个对象传递给邮件发送API（Transport 类） 发送。客户端程序接收邮件时，邮件接收API把接收到的邮件数据封装在Message 类的实例中，客户端程序在使用邮件解析API从这个对象中解析收到的邮件数据。</p>
</li>
<li><p><strong>Transport 类</strong>：<code>javax.mail.Transport</code> 类是<strong>发送邮件</strong>的核心API 类，它的实例对象代表实现了某个邮件发送协议的邮件发送对象，例如 SMTP 协议，客户端程序创建好 Message 对象后，只需要使用邮件发送API 得到 Transport 对象，然后把 Message 对象传递给 Transport 对象，并调用它的发送方法，就可以把邮件发送给指定的 SMTP 服务器。</p>
</li>
<li><p><strong>Store 类</strong>：<code>javax.mail.Store</code> 类是<strong>接收邮件</strong>的核心 API 类，它的实例对象代表实现了某个邮件接收协议的邮件接收对象，例如 POP3 协议，客户端程序接收邮件时，只需要使用邮件接收 API 得到 Store 对象，然后调用 Store 对象的接收方法，就可以从指定的 POP3 服务器获得邮件数据，并把这些邮件数据封装到表示邮件的 Message 对象中。</p>
</li>
<li><p><strong>Session 类</strong>：<code>javax.mail.Session</code> 类用于定义整个应用程序所需的环境信息，以及收集客户端与邮件服务器建立网络连接的<strong>会话信息</strong>，例如邮件服务器的主机名、端口号、采用的邮件发送和接收协议等。Session 对象根据这些信息构建用于邮件收发的 Transport 和 Store 对象，以及为客户端创建 Message 对象时提供信息支持。</p>
</li>
</ul>
<h2 id="开启服务及授权码"><a href="#开启服务及授权码" class="headerlink" title="开启服务及授权码"></a>开启服务及授权码</h2><ul>
<li>某些邮箱服务器为了增加邮箱本身密码的安全性，给 SMTP 客户端设置了独立密码（有的邮箱称为“授权码”）, 对于开启了独立密码的邮箱, 邮箱账户密码必需使用这个独立密码（授权码）。</li>
<li>一般在邮箱的设置里都会有，QQ邮箱也类似，设置后复制授权码，该授权码可以登录邮箱，<strong>需保密</strong></li>
</ul>
<img src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/12/31/683131a691a2fa4afa523fdedd3bc8fa.png" width="70%">



<h1 id="简单邮件"><a href="#简单邮件" class="headerlink" title="简单邮件"></a>简单邮件</h1><ul>
<li>简单邮件，没有附件和图片，即纯文本邮件</li>
</ul>
<h2 id="发送步骤"><a href="#发送步骤" class="headerlink" title="发送步骤"></a>发送步骤</h2><ul>
<li>基本步骤<ol>
<li>连接邮件服务器的参数配置</li>
<li>是否需要设置SSL加密（比如QQ邮箱）</li>
<li>创建包含邮件服务器的网络连接信息的<code>Session</code>对象</li>
<li>创建包含邮件内容的实例对象<code>Message</code></li>
<li>通过session得到<code>transport</code>对象，连接邮箱服务器，发送Message，关闭连接</li>
</ol>
</li>
<li>某些邮箱服务器要求 SMTP 连接需要使用 SSL 安全认证 (为了提高安全性，邮箱支持SSL连接，也可以自己开启)，如果无法连接邮件服务器,，仔细查看控制台打印的 log,，如果有有类似 “连接失败, 要求 SSL 安全连接” 等错误，则开启 SSL 安全连接</li>
<li>SMTP 服务器的端口 (非 SSL 连接的端口一般默认为 25， 可以不添加，如果开启了 SSL 连接，需要改为对应邮箱的 SMTP 服务器的端口，具体可查看对应邮箱服务的帮助，QQ邮箱的SMTP(SLL)端口为465或587, 其他邮箱自行去查看)</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">final</span> String smtpPort = <span class="string">&quot;465&quot;</span>;</span><br><span class="line">prop.setProperty(<span class="string">&quot;mail.smtp.port&quot;</span>, smtpPort);</span><br><span class="line">prop.setProperty(<span class="string">&quot;mail.smtp.socketFactory.class&quot;</span>,<span class="string">&quot;javax.net.ssl.SSLSocketFactory&quot;</span>);</span><br><span class="line">prop.setProperty(<span class="string">&quot;mail.smtp.socketFactory.fallback&quot;</span>, <span class="string">&quot;false&quot;</span>);</span><br><span class="line">prop.setProperty(<span class="string">&quot;mail.smtp.socketFactory.port&quot;</span>, smtpPort);</span><br></pre></td></tr></table></figure>

<ul>
<li>或者设置如下，但要确定包导入成功，最好新建一个lib目录存放<ul>
<li><code>activation-1.1.1.jar</code></li>
<li><code>mail-1.4.7.jar</code></li>
</ul>
</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//关于qq邮箱，还要设置ssl加密，加上一下代码即可,大厂，其他邮箱不需要</span></span><br><span class="line">MailSSLSocketFactory sf = <span class="keyword">new</span> MailSSLSocketFactory();</span><br><span class="line">sf.setTrustAllHosts(<span class="keyword">true</span>);</span><br><span class="line">prop.put(<span class="string">&quot;mail.smtp.ssl.enable&quot;</span>, <span class="string">&quot;true&quot;</span>);</span><br><span class="line">prop.put(<span class="string">&quot;mail.smtp.ssl.socketFactory&quot;</span>, sf);</span><br></pre></td></tr></table></figure>

<h2 id="编码实现"><a href="#编码实现" class="headerlink" title="编码实现"></a>编码实现</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.lzy.mail;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.util.Date;</span><br><span class="line"><span class="keyword">import</span> java.util.Properties;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> javax.mail.*;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> javax.mail.internet.InternetAddress;</span><br><span class="line"><span class="keyword">import</span> javax.mail.internet.MimeMessage;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MailDemo01</span> </span>&#123;</span><br><span class="line">    <span class="comment">//发件人邮箱地址</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> String senderAddress = <span class="string">&quot;2312057536@qq.com&quot;</span>;</span><br><span class="line">    <span class="comment">//收件人邮箱地址</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> String recipientAddress = <span class="string">&quot;2312057536@qq.com&quot;</span>;</span><br><span class="line">    <span class="comment">//发件人邮箱账户名</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> String senderAccount = <span class="string">&quot;2312057536@qq.com&quot;</span>;</span><br><span class="line">    <span class="comment">//发件人邮箱账户密码(独立密码或者授权码)</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> String senderPassword = <span class="string">&quot;npbxxxxfxxmieaae&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        <span class="comment">//连接邮件服务器的参数配置</span></span><br><span class="line">        Properties prop = <span class="keyword">new</span> Properties();</span><br><span class="line">        prop.setProperty(<span class="string">&quot;mail.host&quot;</span>, <span class="string">&quot;smtp.qq.com&quot;</span>); <span class="comment">//设置qq邮箱服务器</span></span><br><span class="line">        prop.setProperty(<span class="string">&quot;mail.transport.protocol&quot;</span>, <span class="string">&quot;smtp&quot;</span>); <span class="comment">//邮件发送协议</span></span><br><span class="line">        prop.setProperty(<span class="string">&quot;mail.smtp.auth&quot;</span>, <span class="string">&quot;true&quot;</span>); <span class="comment">//需要验证用户名密码</span></span><br><span class="line">        </span><br><span class="line">        <span class="comment">//关于qq邮箱，还要设置ssl加密，加上一下代码即可,大厂，其他邮箱不需要</span></span><br><span class="line">        MailSSLSocketFactory sf = <span class="keyword">new</span> MailSSLSocketFactory();</span><br><span class="line">        sf.setTrustAllHosts(<span class="keyword">true</span>);</span><br><span class="line">        prop.put(<span class="string">&quot;mail.smtp.ssl.enable&quot;</span>, <span class="string">&quot;true&quot;</span>);</span><br><span class="line">        prop.put(<span class="string">&quot;mail.smtp.ssl.socketFactory&quot;</span>, sf);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//使用JavaMail发送邮箱的5个步骤</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">//1.创建定义整个程序所需要的环境信息的Session 对象</span></span><br><span class="line">        <span class="comment">//其他:Session session = Session.getInstance(props);</span></span><br><span class="line">        <span class="comment">//qq才有！其他邮箱就不用</span></span><br><span class="line">        Session session = Session.getDefaultInstance(prop, <span class="keyword">new</span> Authenticator() &#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">protected</span> PasswordAuthentication <span class="title">getPasswordAuthentication</span><span class="params">()</span> </span>&#123;</span><br><span class="line">                <span class="comment">//发件人邮箱用户名、授权码</span></span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">new</span> PasswordAuthentication(senderAddress, senderPassword);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//开启Session的debug模式，这样就可以看到程序发送Email的运行状态</span></span><br><span class="line">        session.setDebug(<span class="keyword">true</span>); <span class="comment">//开启后可以看到进程</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">//2.创建邮件的实例对象(利用封装的方法)</span></span><br><span class="line">        Message message = getMimeMessage(session);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//3.通过session得到transport对象</span></span><br><span class="line">        Transport transport = session.getTransport();</span><br><span class="line"></span><br><span class="line">        <span class="comment">//4.使用邮箱的账户名和授权码连接上邮箱服务器</span></span><br><span class="line">        transport.connect(senderAccount, senderPassword);</span><br><span class="line">        </span><br><span class="line"></span><br><span class="line">        <span class="comment">//5.发送邮件</span></span><br><span class="line">        transport.sendMessage(message, message.getAllRecipients());</span><br><span class="line"></span><br><span class="line">        <span class="comment">//如果只想发送给指定的人，可以如下写法</span></span><br><span class="line">        <span class="comment">//transport.sendMessage(message, new Address[]&#123;new InternetAddress(&quot;xxx@qq.com&quot;)&#125;);</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">//6.关闭连接</span></span><br><span class="line">        transport.close();</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> MimeMessage <span class="title">getMimeMessage</span><span class="params">(Session session)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        <span class="comment">//创建一封邮件的实例对象 注意需要传递session</span></span><br><span class="line">        MimeMessage message = <span class="keyword">new</span> MimeMessage(session);</span><br><span class="line">        <span class="comment">//指明邮件的发件人地址</span></span><br><span class="line">        message.setFrom(<span class="keyword">new</span> InternetAddress(senderAddress));</span><br><span class="line">        <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * 设置收件人地址（可以增加多个收件人、抄送、密送），即下面这一行代码书写多行</span></span><br><span class="line"><span class="comment">         * MimeMessage.RecipientType.TO:发送</span></span><br><span class="line"><span class="comment">         * MimeMessage.RecipientType.CC：抄送</span></span><br><span class="line"><span class="comment">         * MimeMessage.RecipientType.BCC：密送</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">        <span class="comment">//指明邮件的收件人地址</span></span><br><span class="line">        message.setRecipient(Message.RecipientType.TO, <span class="keyword">new</span> InternetAddress(recipientAddress));</span><br><span class="line">        <span class="comment">//邮件的标题</span></span><br><span class="line">        message.setSubject(<span class="string">&quot;只包含文本的简单邮件&quot;</span>,<span class="string">&quot;UTF-8&quot;</span>);</span><br><span class="line">        <span class="comment">//邮件的正文文本内容</span></span><br><span class="line">        message.setContent(<span class="string">&quot;&lt;h1 style=&#x27;color:red&#x27;&gt;Hello Babe！&lt;/h1&gt;&quot;</span>, <span class="string">&quot;text/html;charset=UTF-8&quot;</span>);</span><br><span class="line">        <span class="comment">//设置邮件的发送时间,默认立即发送</span></span><br><span class="line">        message.setSentDate(<span class="keyword">new</span> Date());</span><br><span class="line">        <span class="keyword">return</span> message;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>执行完上述代码，然后我们查看收件箱</li>
</ul>
<p><img src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@5a12a6b174a5490ffebc0f707072489c951a04e0/2021/03/28/863a78d3cbe78a407a20d86721ccea0c.png"></p>
<ul>
<li><strong>邮件发送注意实现</strong><ol>
<li>发件人的邮箱账户名和密码：有的邮箱设置了独立密码，还有的必须用授权码登录（qq邮箱），要开启SMTP服务</li>
<li>发件人的SMTP服务器地址：一般是 smtp.xxx.com，比如163邮箱是smtp.163.com，qq邮箱是smtp.qq.com</li>
<li>有些邮箱服务器要求必须要使用 SSL 安全连接;</li>
<li>有可能你收件人地址，发件人地址等信息都正确了，控制台也打印了正确的信息，但是在收件箱就是收不到信息。这是因为可能收件箱服务器拒收了你发的邮件（比如认为你的邮件是广告），这时候可能在垃圾箱里能找到，可能找不到。解决办法是重复的邮件内容不要多次发送，或者更换收件箱试试</li>
</ol>
</li>
</ul>
<h1 id="复杂邮件"><a href="#复杂邮件" class="headerlink" title="复杂邮件"></a>复杂邮件</h1><ul>
<li>复杂邮件指带有附件的邮件，比如文件和图片等</li>
</ul>
<h2 id="MIME"><a href="#MIME" class="headerlink" title="MIME"></a>MIME</h2><ul>
<li><strong>MIME（多用途互联网邮件扩展类型）</strong></li>
<li><code>MimeBodyPart</code><ul>
<li>javax.mail.internet.MimeBodyPart类表示的是一个MIME消息，它和MimeMessage类一样都是从Part接口继承过来。</li>
</ul>
</li>
<li><code>MimeMultipart</code><ul>
<li>javax.mai.internet.MimeMultipart是抽象类Multipart的实现子类，它用来组合多个MIME消息。一个MimeMultipart对象可以包含多代表MIME消息的MimeBodyPart对象</li>
</ul>
</li>
</ul>
<p><img src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@714fa6cbecbcab993b11bef08cb887529e69e171/2021/03/28/4a367bd96934cf9e9696d43096db669a.png"></p>
<h2 id="发送图片"><a href="#发送图片" class="headerlink" title="发送图片"></a>发送图片</h2><ul>
<li>在<code>src</code>资源目录下存放<code>qq登录图片.png</code>图片</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.lzy.mail;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> javax.activation.DataHandler;</span><br><span class="line"><span class="keyword">import</span> javax.activation.FileDataSource;</span><br><span class="line"><span class="keyword">import</span> javax.mail.*;</span><br><span class="line"><span class="keyword">import</span> javax.mail.internet.InternetAddress;</span><br><span class="line"><span class="keyword">import</span> javax.mail.internet.MimeBodyPart;</span><br><span class="line"><span class="keyword">import</span> javax.mail.internet.MimeMessage;</span><br><span class="line"><span class="keyword">import</span> javax.mail.internet.MimeMultipart;</span><br><span class="line"><span class="keyword">import</span> java.util.Properties;</span><br><span class="line"></span><br><span class="line"><span class="comment">//复杂文件 带图片</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MailDemo02</span> </span>&#123;</span><br><span class="line">    <span class="comment">//发件人邮箱地址</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> String senderAddress = <span class="string">&quot;2312057536@qq.com&quot;</span>;</span><br><span class="line">    <span class="comment">//收件人邮箱地址</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> String recipientAddress = <span class="string">&quot;2312057536@qq.com&quot;</span>;</span><br><span class="line">    <span class="comment">//发件人邮箱账户名</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> String senderAccount = <span class="string">&quot;2312057536@qq.com&quot;</span>;</span><br><span class="line">    <span class="comment">//发件人邮箱账户密码(独立密码或者授权码)</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> String senderPassword = <span class="string">&quot;xxxxxxxxx&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        <span class="comment">//连接邮件服务器的参数配置</span></span><br><span class="line">        Properties prop = <span class="keyword">new</span> Properties();</span><br><span class="line">        prop.setProperty(<span class="string">&quot;mail.host&quot;</span>, <span class="string">&quot;smtp.qq.com&quot;</span>); <span class="comment">//设置qq邮箱服务器</span></span><br><span class="line">        prop.setProperty(<span class="string">&quot;mail.transport.protocol&quot;</span>, <span class="string">&quot;smtp&quot;</span>); <span class="comment">//邮件发送协议</span></span><br><span class="line">        prop.setProperty(<span class="string">&quot;mail.smtp.auth&quot;</span>, <span class="string">&quot;true&quot;</span>); <span class="comment">//需要验证用户名密码</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">//关于qq邮箱，还要设置ssl加密，加上一下代码即可,大厂，其他邮箱不需要</span></span><br><span class="line">        <span class="keyword">final</span> String smtpPort = <span class="string">&quot;465&quot;</span>;</span><br><span class="line">        prop.setProperty(<span class="string">&quot;mail.smtp.port&quot;</span>, smtpPort);</span><br><span class="line">        prop.setProperty(<span class="string">&quot;mail.smtp.socketFactory.class&quot;</span>, <span class="string">&quot;javax.net.ssl.SSLSocketFactory&quot;</span>);</span><br><span class="line">        prop.setProperty(<span class="string">&quot;mail.smtp.socketFactory.fallback&quot;</span>, <span class="string">&quot;false&quot;</span>);</span><br><span class="line">        prop.setProperty(<span class="string">&quot;mail.smtp.socketFactory.port&quot;</span>, smtpPort);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//使用JavaMail发送邮箱的5个步骤</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">//1.创建定义整个程序所需要的环境信息的Session 对象</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">//qq才有！其他邮箱就不用</span></span><br><span class="line">        Session session = Session.getDefaultInstance(prop, <span class="keyword">new</span> Authenticator() &#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">protected</span> PasswordAuthentication <span class="title">getPasswordAuthentication</span><span class="params">()</span> </span>&#123;</span><br><span class="line">                <span class="comment">//发件人邮箱用户名、授权码</span></span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">new</span> PasswordAuthentication(senderAddress, senderPassword);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//开启Session的debug模式，这样就可以看到程序发送Email的运行状态</span></span><br><span class="line">        session.setDebug(<span class="keyword">true</span>); <span class="comment">//开启后可以看到进程</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">//2. 创建邮件的实例对象</span></span><br><span class="line">        Message message = getMimeMessage(session);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//3.通过session得到transport对象</span></span><br><span class="line">        Transport ts = session.getTransport();</span><br><span class="line"></span><br><span class="line">        <span class="comment">//4.使用邮箱的账户名和授权码连接上邮箱服务器</span></span><br><span class="line">        ts.connect(senderAccount, senderPassword);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//5.//发送邮件，并发送到所有收件人地址，message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人, 密送人</span></span><br><span class="line">        ts.sendMessage(message, message.getAllRecipients());</span><br><span class="line"></span><br><span class="line">        <span class="comment">//6.关闭连接</span></span><br><span class="line">        ts.close();</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/*获得创建一封邮件的实例对象*/</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> MimeMessage <span class="title">getMimeMessage</span><span class="params">(Session session)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        <span class="comment">//1. 创建一封邮件的实例对象</span></span><br><span class="line">        MimeMessage message = <span class="keyword">new</span> MimeMessage(session);</span><br><span class="line">        <span class="comment">//2. 设置发件人地址</span></span><br><span class="line">        message.setFrom(<span class="keyword">new</span> InternetAddress(senderAddress));</span><br><span class="line">        <span class="comment">//3. 设置收件人地址(可以增加多个收件人、发送TO、抄送CC、密送BCC)</span></span><br><span class="line">        message.setRecipient(MimeMessage.RecipientType.TO, <span class="keyword">new</span> InternetAddress(recipientAddress));</span><br><span class="line">        <span class="comment">//4. 设置邮件的标题</span></span><br><span class="line">        message.setSubject(<span class="string">&quot;带图片的文件&quot;</span>, <span class="string">&quot;UTF-8&quot;</span>);</span><br><span class="line">        <span class="comment">//下面是设置邮件正文</span></span><br><span class="line">        <span class="comment">//msg.setContent(&quot;简单的纯文本邮件！&quot;, &quot;text/html;charset=UTF-8&quot;);</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">//准备邮件数据</span></span><br><span class="line">        <span class="comment">// 5. 创建图片&quot;节点&quot;</span></span><br><span class="line">        MimeBodyPart image = <span class="keyword">new</span> MimeBodyPart();</span><br><span class="line">        <span class="comment">// 读取本地文件 DataHandler：数据处理</span></span><br><span class="line">        DataHandler dh = <span class="keyword">new</span> DataHandler(<span class="keyword">new</span> FileDataSource(<span class="string">&quot;D:\\IDEA_Workspace\\FIle_Mail\\File_Demo01\\src\\qq登录图片.png&quot;</span>));</span><br><span class="line">        <span class="comment">// 将图片数据添加到&quot;节点&quot;</span></span><br><span class="line">        image.setDataHandler(dh);</span><br><span class="line">        <span class="comment">// 为&quot;节点&quot;设置一个唯一编号（在文本&quot;节点&quot;将引用该ID）</span></span><br><span class="line">        image.setContentID(<span class="string">&quot;qq_img&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//准备正文数据</span></span><br><span class="line">        <span class="comment">//6. 创建文本&quot;节点&quot;</span></span><br><span class="line">        MimeBodyPart text = <span class="keyword">new</span> MimeBodyPart();</span><br><span class="line">        <span class="comment">// 这里添加图片的方式是将整个图片包含到邮件内容中, 这里以cid:id的形式引用上面设置的ID，实际上也可以以 http 链接的形式添加网络图片</span></span><br><span class="line">        text.setContent(<span class="string">&quot;这是一封邮件正文带图片&lt;img src=&#x27;cid:qq_img&#x27;&gt;的邮件&quot;</span>, <span class="string">&quot;text/html;charset=UTF-8&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//7. 描述数据关系(将 文本 和 图片&quot;节点&quot;合成一个混合&quot;节点&quot;)</span></span><br><span class="line">        MimeMultipart mm = <span class="keyword">new</span> MimeMultipart();</span><br><span class="line">        mm.addBodyPart(text);</span><br><span class="line">        mm.addBodyPart(image);</span><br><span class="line">        mm.setSubType(<span class="string">&quot;related&quot;</span>); <span class="comment">//关联关系,附件&quot;mixed&quot;</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">//8. 设置到消息中，保存修改</span></span><br><span class="line">        message.setContent(mm); <span class="comment">//把最后编辑好的邮件放到消息中</span></span><br><span class="line">        message.saveChanges(); <span class="comment">//保存修改</span></span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> message;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>运行结果</li>
</ul>
<p><img src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@dd257db7249b3cec2edf397104dbc329eddaf172/2021/03/29/0914958172bba016485ee2c793135fbc.png"></p>
<h2 id="发送图片和附件"><a href="#发送图片和附件" class="headerlink" title="发送图片和附件"></a>发送图片和附件</h2><ul>
<li>在<code>src</code>资源目录下存放<code>附件.txt</code>文件</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.lzy.mail;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.sun.mail.util.MailSSLSocketFactory;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> javax.activation.DataHandler;</span><br><span class="line"><span class="keyword">import</span> javax.activation.FileDataSource;</span><br><span class="line"><span class="keyword">import</span> javax.mail.*;</span><br><span class="line"><span class="keyword">import</span> javax.mail.internet.*;</span><br><span class="line"><span class="keyword">import</span> java.util.Properties;</span><br><span class="line"></span><br><span class="line"><span class="comment">//复杂文件 带图片 带附件</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MailDemo03</span> </span>&#123;</span><br><span class="line">    <span class="comment">//发件人邮箱地址</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> String senderAddress = <span class="string">&quot;2312057536@qq.com&quot;</span>;</span><br><span class="line">    <span class="comment">//收件人邮箱地址</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> String recipientAddress = <span class="string">&quot;2312057536@qq.com&quot;</span>;</span><br><span class="line">    <span class="comment">//发件人邮箱账户名</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> String senderAccount = <span class="string">&quot;2312057536@qq.com&quot;</span>;</span><br><span class="line">    <span class="comment">//发件人邮箱账户密码(独立密码或者授权码)</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> String senderPassword = <span class="string">&quot;npbxxxxxxxxe&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        <span class="comment">//连接邮件服务器的参数配置</span></span><br><span class="line">        Properties prop = <span class="keyword">new</span> Properties();</span><br><span class="line">        prop.setProperty(<span class="string">&quot;mail.host&quot;</span>, <span class="string">&quot;smtp.qq.com&quot;</span>); <span class="comment">//设置qq邮箱服务器</span></span><br><span class="line">        prop.setProperty(<span class="string">&quot;mail.transport.protocol&quot;</span>, <span class="string">&quot;smtp&quot;</span>); <span class="comment">//邮件发送协议</span></span><br><span class="line">        prop.setProperty(<span class="string">&quot;mail.smtp.auth&quot;</span>, <span class="string">&quot;true&quot;</span>); <span class="comment">//需要验证用户名密码</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">//关于qq邮箱，还要设置ssl加密，加上一下代码即可,大厂，其他邮箱不需要</span></span><br><span class="line">        <span class="keyword">final</span> String smtpPort = <span class="string">&quot;465&quot;</span>;</span><br><span class="line">        prop.setProperty(<span class="string">&quot;mail.smtp.port&quot;</span>, smtpPort);</span><br><span class="line">        prop.setProperty(<span class="string">&quot;mail.smtp.socketFactory.class&quot;</span>, <span class="string">&quot;javax.net.ssl.SSLSocketFactory&quot;</span>);</span><br><span class="line">        prop.setProperty(<span class="string">&quot;mail.smtp.socketFactory.fallback&quot;</span>, <span class="string">&quot;false&quot;</span>);</span><br><span class="line">        prop.setProperty(<span class="string">&quot;mail.smtp.socketFactory.port&quot;</span>, smtpPort);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//使用JavaMail发送邮箱的5个步骤</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">//1.创建定义整个程序所需要的环境信息的Session 对象</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">//qq才有！其他邮箱就不用</span></span><br><span class="line">        Session session = Session.getDefaultInstance(prop, <span class="keyword">new</span> Authenticator() &#123;</span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">protected</span> PasswordAuthentication <span class="title">getPasswordAuthentication</span><span class="params">()</span> </span>&#123;</span><br><span class="line">                <span class="comment">//发件人邮箱用户名、授权码</span></span><br><span class="line">                <span class="keyword">return</span> <span class="keyword">new</span> PasswordAuthentication(senderAddress, senderPassword);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//开启Session的debug模式，这样就可以看到程序发送Email的运行状态</span></span><br><span class="line">        session.setDebug(<span class="keyword">true</span>); <span class="comment">//开启后可以看到进程</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">//2. 创建邮件的实例对象</span></span><br><span class="line">        Message message = getMimeMessage(session);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//3.通过session得到transport对象</span></span><br><span class="line">        Transport ts = session.getTransport();</span><br><span class="line"></span><br><span class="line">        <span class="comment">//4.使用邮箱的账户名和授权码连接上邮箱服务器</span></span><br><span class="line">        ts.connect(senderAccount, senderPassword);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//5.//发送邮件，并发送到所有收件人地址，message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人, 密送人</span></span><br><span class="line">        ts.sendMessage(message, message.getAllRecipients());</span><br><span class="line"></span><br><span class="line">        <span class="comment">//6.关闭连接</span></span><br><span class="line">        ts.close();</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> MimeMessage <span class="title">getMimeMessage</span><span class="params">(Session session)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        <span class="comment">//1. 创建一封邮件的实例对象</span></span><br><span class="line">        MimeMessage message = <span class="keyword">new</span> MimeMessage(session);</span><br><span class="line">        <span class="comment">//2. 设置发件人地址</span></span><br><span class="line">        message.setFrom(<span class="keyword">new</span> InternetAddress(senderAddress));</span><br><span class="line">        <span class="comment">//3. 设置收件人地址(可以增加多个收件人、发送TO、抄送CC、密送BCC)</span></span><br><span class="line">        message.setRecipient(MimeMessage.RecipientType.TO, <span class="keyword">new</span> InternetAddress(recipientAddress));</span><br><span class="line">        <span class="comment">//4. 设置邮件的标题</span></span><br><span class="line">        message.setSubject(<span class="string">&quot;带图片和附件的邮件&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">/*</span></span><br><span class="line"><span class="comment">        编写邮件的内容</span></span><br><span class="line"><span class="comment">        1.图片</span></span><br><span class="line"><span class="comment">        2.附件</span></span><br><span class="line"><span class="comment">        3.文本</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">//图片</span></span><br><span class="line">        MimeBodyPart img = <span class="keyword">new</span> MimeBodyPart();</span><br><span class="line">        <span class="comment">//图片需要经过数据处理。。。 DataHandler：数据处理</span></span><br><span class="line">        DataHandler dh1 = <span class="keyword">new</span> DataHandler(<span class="keyword">new</span> FileDataSource(<span class="string">&quot;D:\\IDEA_Workspace\\FIle_Mail\\File_Demo01\\src\\qq登录图片.png&quot;</span>));</span><br><span class="line">        img.setDataHandler(dh1); <span class="comment">//在我们的图片节点中放入这个处理的图片数据</span></span><br><span class="line">        img.setContentID(<span class="string">&quot;qq_img&quot;</span>); <span class="comment">//给图片设置一个ID，我们可以在文件节点内容中引用</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">//文本</span></span><br><span class="line">        MimeBodyPart text = <span class="keyword">new</span> MimeBodyPart();</span><br><span class="line">        text.setContent(<span class="string">&quot;这个带图片&lt;img src=&#x27;cid:qq_img&#x27;&gt;的邮件&quot;</span>, <span class="string">&quot;text/html;charset=UTF-8&quot;</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//创建附件&quot;节点&quot;</span></span><br><span class="line">        MimeBodyPart attachment = <span class="keyword">new</span> MimeBodyPart();</span><br><span class="line">        <span class="comment">// 读取本地文件</span></span><br><span class="line">        DataHandler dh2 = <span class="keyword">new</span> DataHandler(<span class="keyword">new</span> FileDataSource(<span class="string">&quot;D:\\IDEA_Workspace\\FIle_Mail\\File_Demo01\\src\\附件.txt&quot;</span>));</span><br><span class="line">        attachment.setDataHandler(dh2);</span><br><span class="line">        <span class="comment">// 设置附件的文件名（需要编码）</span></span><br><span class="line">        <span class="comment">//attachment.setFileName(&quot;附件.txt&quot;);</span></span><br><span class="line">         attachment.setFileName(MimeUtility.encodeText(dh2.getName()));</span><br><span class="line">        </span><br><span class="line">         <span class="comment">//拼装邮件正文内容</span></span><br><span class="line">        MimeMultipart multipart1 = <span class="keyword">new</span> MimeMultipart();</span><br><span class="line">        multipart1.addBodyPart(img);</span><br><span class="line">        multipart1.addBodyPart(text);</span><br><span class="line">        multipart1.setSubType(<span class="string">&quot;related&quot;</span>); <span class="comment">//1.文本和图片内嵌成功</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">//new MimeBodyPart().setContent(multipart1);将拼装好的正文内容设为主体</span></span><br><span class="line">        MimeBodyPart contextText = <span class="keyword">new</span> MimeBodyPart();</span><br><span class="line">        contextText.setContent(multipart1);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//拼接附件</span></span><br><span class="line">        MimeMultipart allFile = <span class="keyword">new</span> MimeMultipart();</span><br><span class="line">        allFile.addBodyPart(attachment); <span class="comment">//附件</span></span><br><span class="line">        allFile.addBodyPart(contextText); <span class="comment">//正文</span></span><br><span class="line">        allFile.setSubType(<span class="string">&quot;mixed&quot;</span>); <span class="comment">//正文和附件都存在邮件中，所有类型都设为mixed</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        <span class="comment">//设置到消息中，保存修改</span></span><br><span class="line">        message.setContent(allFile); <span class="comment">//把最后编辑好的邮件放到消息中</span></span><br><span class="line">        message.saveChanges(); <span class="comment">//保存修改</span></span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> message;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>运行结果</li>
</ul>
<p><img src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@c013a7d5dc410dfb7cfe6a7fb884265151984b1d/2021/03/29/f2748a2f9ef5160a463ace6f6c236760.png"></p>
<h1 id="接收邮件"><a href="#接收邮件" class="headerlink" title="接收邮件"></a>接收邮件</h1><ul>
<li>接收邮件用处不多，稍作了解即可</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br></pre></td><td class="code"><pre><span class="line"> <span class="keyword">package</span> com.lzyblog.mail;</span><br><span class="line"> </span><br><span class="line"><span class="keyword">import</span> java.util.Properties;</span><br><span class="line"><span class="keyword">import</span> javax.mail.Address;</span><br><span class="line"><span class="keyword">import</span> javax.mail.Folder;</span><br><span class="line"><span class="keyword">import</span> javax.mail.Message;</span><br><span class="line"><span class="keyword">import</span> javax.mail.Session;</span><br><span class="line"><span class="keyword">import</span> javax.mail.Store;</span><br><span class="line"> </span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">RecipientMail</span> </span>&#123;</span><br><span class="line">    <span class="comment">//收件人地址</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> String recipientAddress = <span class="string">&quot;xxx@163.com&quot;</span>;</span><br><span class="line">    <span class="comment">//收件人账户名</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> String recipientAccount = <span class="string">&quot;xxx&quot;</span>;</span><br><span class="line">    <span class="comment">//收件人账户密码</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> String recipientPassword = <span class="string">&quot;xxx&quot;</span>;</span><br><span class="line">     </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        <span class="comment">//1、连接邮件服务器的参数配置</span></span><br><span class="line">        Properties props = <span class="keyword">new</span> Properties();</span><br><span class="line">        <span class="comment">//设置传输协议</span></span><br><span class="line">        props.setProperty(<span class="string">&quot;mail.store.protocol&quot;</span>, <span class="string">&quot;pop3&quot;</span>);</span><br><span class="line">        <span class="comment">//设置收件人的POP3服务器</span></span><br><span class="line">        props.setProperty(<span class="string">&quot;mail.pop3.host&quot;</span>, <span class="string">&quot;pop3.163.com&quot;</span>);</span><br><span class="line">        <span class="comment">//2、创建定义整个应用程序所需的环境信息的 Session 对象</span></span><br><span class="line">        Session session = Session.getInstance(props);</span><br><span class="line">        <span class="comment">//设置调试信息在控制台打印出来</span></span><br><span class="line">        <span class="comment">//session.setDebug(true);</span></span><br><span class="line">         </span><br><span class="line">        Store store = session.getStore(<span class="string">&quot;pop3&quot;</span>);</span><br><span class="line">        <span class="comment">//连接收件人POP3服务器</span></span><br><span class="line">        store.connect(<span class="string">&quot;pop3.163.com&quot;</span>, recipientAccount, recipientPassword);</span><br><span class="line">        <span class="comment">//获得用户的邮件账户，注意通过pop3协议获取某个邮件夹的名称只能为inbox</span></span><br><span class="line">        Folder folder = store.getFolder(<span class="string">&quot;inbox&quot;</span>);</span><br><span class="line">        <span class="comment">//设置对邮件账户的访问权限</span></span><br><span class="line">        folder.open(Folder.READ_WRITE);</span><br><span class="line">         </span><br><span class="line">        <span class="comment">//得到邮件账户的所有邮件信息</span></span><br><span class="line">        Message [] messages = folder.getMessages();</span><br><span class="line">        <span class="keyword">for</span>(<span class="keyword">int</span> i = <span class="number">0</span> ; i &lt; messages.length ; i++)&#123;</span><br><span class="line">            <span class="comment">//获得邮件主题</span></span><br><span class="line">            String subject = messages[i].getSubject();</span><br><span class="line">            <span class="comment">//获得邮件发件人</span></span><br><span class="line">            Address[] from = messages[i].getFrom();</span><br><span class="line">            <span class="comment">//获取邮件内容（包含邮件内容的html代码）</span></span><br><span class="line">            String content = (String) messages[i].getContent();</span><br><span class="line">        &#125;</span><br><span class="line">         </span><br><span class="line">        <span class="comment">//关闭邮件夹对象</span></span><br><span class="line">        folder.close();</span><br><span class="line">        <span class="comment">//关闭连接对象</span></span><br><span class="line">        store.close();</span><br><span class="line">    &#125;</span><br><span class="line"> </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h1 id="注册邮件实例"><a href="#注册邮件实例" class="headerlink" title="注册邮件实例"></a>注册邮件实例</h1><h2 id="前端界面"><a href="#前端界面" class="headerlink" title="前端界面"></a>前端界面</h2><ul>
<li>注册界面<code>index.jsp</code></li>
</ul>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">%@</span> <span class="attr">page</span> <span class="attr">contentType</span>=<span class="string">&quot;text/html;charset=UTF-8&quot;</span> <span class="attr">language</span>=<span class="string">&quot;java&quot;</span> %&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">title</span>&gt;</span>注册<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">form</span> <span class="attr">action</span>=<span class="string">&quot;$&#123;pageContext.request.contextPath&#125;/RegisterServlet&quot;</span> <span class="attr">method</span>=<span class="string">&quot;post&quot;</span>&gt;</span></span><br><span class="line">    用户名：<span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">&quot;text&quot;</span> <span class="attr">name</span>=<span class="string">&quot;username&quot;</span>&gt;</span> <span class="tag">&lt;<span class="name">br</span>/&gt;</span></span><br><span class="line">    密码：<span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">&quot;password&quot;</span> <span class="attr">name</span>=<span class="string">&quot;password&quot;</span>&gt;</span> <span class="tag">&lt;<span class="name">br</span>/&gt;</span></span><br><span class="line">    邮箱：<span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">&quot;text&quot;</span> <span class="attr">name</span>=<span class="string">&quot;email&quot;</span>&gt;</span> <span class="tag">&lt;<span class="name">br</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">&quot;submit&quot;</span> <span class="attr">value</span>=<span class="string">&quot;注册&quot;</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;/<span class="name">form</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></table></figure>

<ul>
<li>注册成功提醒界面<code>info.jsp</code></li>
</ul>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">%@</span> <span class="attr">page</span> <span class="attr">contentType</span>=<span class="string">&quot;text/html;charset=UTF-8&quot;</span> <span class="attr">language</span>=<span class="string">&quot;java&quot;</span> %&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">title</span>&gt;</span>Title<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">h1</span>&gt;</span>网站温馨提示<span class="tag">&lt;/<span class="name">h1</span>&gt;</span></span><br><span class="line">$&#123;message&#125;</span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h2 id="实体类"><a href="#实体类" class="headerlink" title="实体类"></a>实体类</h2><ul>
<li>在com.lzy.pojo包下，创建<code>User</code>实体类</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.lzy.pojo;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> lombok.Data;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Data</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">User</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> String username;</span><br><span class="line">    <span class="keyword">private</span> String password;</span><br><span class="line">    <span class="keyword">private</span> String email;</span><br><span class="line">    <span class="comment">//无参和有参构造方法</span></span><br><span class="line">    <span class="comment">//getter和setter方法</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">User</span><span class="params">(String username, String password, String email)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.username = username;</span><br><span class="line">        <span class="keyword">this</span>.password = password;</span><br><span class="line">        <span class="keyword">this</span>.email = email;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="Servlet"><a href="#Servlet" class="headerlink" title="Servlet"></a>Servlet</h2><ul>
<li>在com.lzy.servlet创建<code>RegisterServlet</code></li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.lzy.servlet;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.lzy.pojo.User;</span><br><span class="line"><span class="keyword">import</span> com.lzy.utils.Sendmail;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> javax.servlet.ServletException;</span><br><span class="line"><span class="keyword">import</span> javax.servlet.http.HttpServlet;</span><br><span class="line"><span class="keyword">import</span> javax.servlet.http.HttpServletRequest;</span><br><span class="line"><span class="keyword">import</span> javax.servlet.http.HttpServletResponse;</span><br><span class="line"><span class="keyword">import</span> java.io.IOException;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">RRegisterServlet</span> <span class="keyword">extends</span> <span class="title">HttpServlet</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">doGet</span><span class="params">(HttpServletRequest req, HttpServletResponse resp)</span> <span class="keyword">throws</span> ServletException, IOException </span>&#123;</span><br><span class="line">        <span class="comment">//接受用户请求，封装成对象</span></span><br><span class="line">        String username = req.getParameter(<span class="string">&quot;username&quot;</span>);</span><br><span class="line">        String password = req.getParameter(<span class="string">&quot;password&quot;</span>);</span><br><span class="line">        String email = req.getParameter(<span class="string">&quot;email&quot;</span>);</span><br><span class="line"></span><br><span class="line">        User user = <span class="keyword">new</span> User(username, password, email);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//用户注册成功之后，给用户发送一封邮件</span></span><br><span class="line">        <span class="comment">//我们使用多线程来专门发送邮件，防止出现耗时，和网站注册人数过多的情况；</span></span><br><span class="line">        Sendmail send = <span class="keyword">new</span> Sendmail(user);</span><br><span class="line">        <span class="comment">//启动线程，线程启动之后就会执行run方法来发送邮件</span></span><br><span class="line">        send.start();</span><br><span class="line"></span><br><span class="line">        <span class="comment">//注册用户</span></span><br><span class="line">        req.setAttribute(<span class="string">&quot;message&quot;</span>, <span class="string">&quot;注册成功，我们已经发了一封带了注册信息的电子邮件，请查收！如网络不稳定，可能过会儿才能收到！！&quot;</span>);</span><br><span class="line">        req.getRequestDispatcher(<span class="string">&quot;info.jsp&quot;</span>).forward(req, resp);</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">doPost</span><span class="params">(HttpServletRequest req, HttpServletResponse resp)</span> <span class="keyword">throws</span> ServletException, IOException </span>&#123;</span><br><span class="line">        doGet(req, resp);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="邮件发送工具类"><a href="#邮件发送工具类" class="headerlink" title="邮件发送工具类"></a>邮件发送工具类</h2><ul>
<li>在com.lzy.utils下，创建工具类<code>Sendmail</code></li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.lzy.utils;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.lzy.pojo.User;</span><br><span class="line"><span class="keyword">import</span> com.sun.mail.util.MailSSLSocketFactory;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> javax.mail.*;</span><br><span class="line"><span class="keyword">import</span> javax.mail.internet.InternetAddress;</span><br><span class="line"><span class="keyword">import</span> javax.mail.internet.MimeMessage;</span><br><span class="line"><span class="keyword">import</span> java.util.Properties;</span><br><span class="line"></span><br><span class="line"><span class="comment">//网站3秒原则：一个网页白屏加载超过3秒以上用户体验差</span></span><br><span class="line"><span class="comment">//多线程实现用户体验 （异步处理）</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Sendmail</span> <span class="keyword">extends</span> <span class="title">Thread</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//用于给用户发送邮件的邮箱</span></span><br><span class="line">    <span class="keyword">private</span> String from = <span class="string">&quot;2312057536@qq.com&quot;</span>;</span><br><span class="line">    <span class="comment">//邮箱的用户名</span></span><br><span class="line">    <span class="keyword">private</span> String username = <span class="string">&quot;2312057536@qq.com&quot;</span>;</span><br><span class="line">    <span class="comment">//邮箱的密码 qq授权码</span></span><br><span class="line">    <span class="keyword">private</span> String password = <span class="string">&quot;nxxxbxxxxxxxe&quot;</span>;</span><br><span class="line">    <span class="comment">//发送邮箱的服务地址</span></span><br><span class="line">    <span class="keyword">private</span> String host = <span class="string">&quot;smtp.qq.com&quot;</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> User user;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Sendmail</span><span class="params">(User user)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.user = user;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//重写run方法的实现，在run方法中发送邮件给指定的用户</span></span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            Properties prop = <span class="keyword">new</span> Properties();</span><br><span class="line">            prop.setProperty(<span class="string">&quot;mail.host&quot;</span>, <span class="string">&quot;smtp.qq.com&quot;</span>); <span class="comment">//设置qq邮箱服务器</span></span><br><span class="line">            prop.setProperty(<span class="string">&quot;mail.transport.protocol&quot;</span>, <span class="string">&quot;smtp&quot;</span>); <span class="comment">//邮件发送协议</span></span><br><span class="line">            prop.setProperty(<span class="string">&quot;mail.smtp.auth&quot;</span>, <span class="string">&quot;true&quot;</span>); <span class="comment">//需要验证用户名密码</span></span><br><span class="line"></span><br><span class="line">            <span class="comment">//关于qq邮箱，还要设置ssl加密，加上一下代码即可,大厂，其他邮箱不需要</span></span><br><span class="line">            MailSSLSocketFactory sf = <span class="keyword">new</span> MailSSLSocketFactory();</span><br><span class="line">            sf.setTrustAllHosts(<span class="keyword">true</span>);</span><br><span class="line">            prop.put(<span class="string">&quot;mail.smtp.ssl.enable&quot;</span>, <span class="string">&quot;true&quot;</span>);</span><br><span class="line">            prop.put(<span class="string">&quot;mail.smtp.ssl.socketFactory&quot;</span>, sf);</span><br><span class="line"></span><br><span class="line">            <span class="comment">//使用JavaMail发送邮箱的5个步骤</span></span><br><span class="line"></span><br><span class="line">            <span class="comment">//1.创建定义整个程序所需要的环境信息的Session 对象</span></span><br><span class="line"></span><br><span class="line">            <span class="comment">//qq才有！其他邮箱就不用</span></span><br><span class="line">            Session session = Session.getDefaultInstance(prop, <span class="keyword">new</span> Authenticator() &#123;</span><br><span class="line">                <span class="meta">@Override</span></span><br><span class="line">                <span class="function"><span class="keyword">protected</span> PasswordAuthentication <span class="title">getPasswordAuthentication</span><span class="params">()</span> </span>&#123;</span><br><span class="line">                    <span class="comment">//发件人邮箱用户名、授权码</span></span><br><span class="line">                    <span class="keyword">return</span> <span class="keyword">new</span> PasswordAuthentication(from, password);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;);</span><br><span class="line"></span><br><span class="line">            <span class="comment">//开启Session的debug模式，这样就可以看到程序发送Email的运行状态</span></span><br><span class="line">            session.setDebug(<span class="keyword">true</span>); <span class="comment">//开启后可以看到进程</span></span><br><span class="line"></span><br><span class="line">            <span class="comment">//2.通过session得到transport对象</span></span><br><span class="line">            Transport ts = <span class="keyword">null</span>;</span><br><span class="line">            ts = session.getTransport();</span><br><span class="line"></span><br><span class="line">            <span class="comment">//3.使用邮箱的用户名和授权码连接上邮箱服务器</span></span><br><span class="line">            ts.connect(<span class="string">&quot;smtp.qq.com&quot;</span>, from, password);</span><br><span class="line"></span><br><span class="line">            <span class="comment">//4.创建邮件</span></span><br><span class="line"></span><br><span class="line">            <span class="comment">//创建邮件对象 注意需要传递session</span></span><br><span class="line">            MimeMessage message = <span class="keyword">new</span> MimeMessage(session);</span><br><span class="line"></span><br><span class="line">            <span class="comment">//指明邮件的发件人</span></span><br><span class="line">            message.setFrom(<span class="keyword">new</span> InternetAddress(from));</span><br><span class="line"></span><br><span class="line">            <span class="comment">//指明邮件的收件人</span></span><br><span class="line">            message.setRecipient(Message.RecipientType.TO, <span class="keyword">new</span> InternetAddress(user.getEmail()));</span><br><span class="line"></span><br><span class="line">            <span class="comment">//邮件的标题</span></span><br><span class="line">            message.setSubject(<span class="string">&quot;用户注册邮件&quot;</span>);</span><br><span class="line">            String info = <span class="string">&quot;恭喜注册成功，您的用户名：&quot;</span> + user.getUsername() + <span class="string">&quot;，您的密码&quot;</span> + user.getPassword() + <span class="string">&quot;，请妥善保管，如有问题请联系网站客服！！&quot;</span>;</span><br><span class="line"></span><br><span class="line">            <span class="comment">//邮件的文本内容</span></span><br><span class="line">            message.setContent(info, <span class="string">&quot;text/html;charset=UTF-8&quot;</span>);</span><br><span class="line"></span><br><span class="line">            <span class="comment">//5.发送邮件</span></span><br><span class="line">            ts.sendMessage(message, message.getAllRecipients());</span><br><span class="line"></span><br><span class="line">            <span class="comment">//6.关闭连接</span></span><br><span class="line">            ts.close();</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="运行结果"><a href="#运行结果" class="headerlink" title="运行结果"></a>运行结果</h2><ul>
<li><code>index.jsp</code>前端界面</li>
</ul>
<p><img src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@d0e0a900c8aee05b3883c325b1c771fcd7365d9d/2021/03/29/6bde1bcb175ed6fb3fa8ead13bb4198c.png"></p>
<ul>
<li><code>info.jsp</code>提醒界面</li>
</ul>
<p><img src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@5e7e0ef5079a330211c5038c6591b9256931225d/2021/03/29/6ea8f3689ad289821bac1a811bc93e9c.png"></p>
<ul>
<li>收到邮件如下</li>
</ul>
<p><img src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@b76773df9573fff1f6607411222a394b24535e70/2021/03/29/975aba334f8eb824ddb3d226b4265dc1.png"></p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">小李博客</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://xiaoliblog.cn">https://xiaoliblog.cn</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="http://xiaoliblog.cn" target="_blank">小李博客</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/%E4%BC%81%E4%B8%9A%E5%B8%B8%E7%94%A8%E6%8A%80%E6%9C%AF/">企业常用技术</a></div><div class="post_share"><div class="social-share" data-image="https://cdn.jsdelivr.net/gh/xiaoliblog/image@49db1e1882ba97dcb3a0c2be5a580006f80f1f4f/2021/01/24/7309dc108232cf99fd79b144f350f4f5.png" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><div class="post-reward"><div class="reward-button button--animated"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="/img/wechat.png" target="_blank"><img class="post-qr-code-img" src="/img/wechat.png" alt="微信"/></a><div class="post-qr-code-desc">微信</div></li><li class="reward-item"><a href="/img/alipay.png" target="_blank"><img class="post-qr-code-img" src="/img/alipay.png" alt="支付宝"/></a><div class="post-qr-code-desc">支付宝</div></li></ul></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/page/vscode.html"><img class="prev-cover" src="https://cdn.jsdelivr.net/gh/lzyblog/image@main/2021/01/03/24ca35f9bc80d99b048196fa8b73b300.png" onerror="onerror=null;src='https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/11/19/bd16b394f7359083b1f6072a67e3f968.png'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">Visual Studio Code常用插件</div></div></a></div><div class="next-post pull-right"><a href="/page/hexo03.html"><img class="next-cover" src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@2b4802e64dda1cdfead2db084a07b179beaff7dc/2021/03/29/082954b9ca0f481522271eaecce8d840.png" onerror="onerror=null;src='https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/11/19/bd16b394f7359083b1f6072a67e3f968.png'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">Hexo博客结构及配置文件解析</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span> 相关推荐</span></div><div class="relatedPosts-list"><div><a href="/page/Ngrok.html" title="Ngrok内网穿透技术"><img class="cover" src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@325711b4582f41dc46b8fd9042f1815f684f6a3e/2021/03/21/d8f7dea318fe22b1b6efca6de912d9c4.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-03-21</div><div class="title">Ngrok内网穿透技术</div></div></a></div><div><a href="/page/server.html" title="服务器购买及宝塔部署环境说明"><img class="cover" src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@b8cd50b76d641acb7d91939cf488d974ac872cde/2021/03/05/b9345f8f1e57bd17d1607475a3d62640.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-04-05</div><div class="title">服务器购买及宝塔部署环境说明</div></div></a></div><div><a href="/page/EasyEscel.html" title="POI及EasyExcel技术"><img class="cover" src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@9e9580790103438844006d318376ce0705ea3391/2021/03/21/d1526753cb5cf7b4ca23e2441600c3dc.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-03-21</div><div class="title">POI及EasyExcel技术</div></div></a></div><div><a href="/page/Alipay.html" title="支付宝支付对接"><img class="cover" src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@61a9b6a6e09e4bda38bb08e3104b717885beaee5/2021/04/29/c3fa51f9cf14e90d9e5a7aa8814dd041.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-04-28</div><div class="title">支付宝支付对接</div></div></a></div><div><a href="/page/message.html" title="第三方短信接入"><img class="cover" src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@3df69ce79a43aead58a4cff7b7fa87893cc5b560/2021/03/21/225a42983e955972e4038a3f1e4bf592.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-03-21</div><div class="title">第三方短信接入</div></div></a></div><div><a href="/page/WeChatpay.html" title="微信支付对接"><img class="cover" src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@f2f670b92ea149650ffa7834354fc90284f2f44a/2021/04/29/5bdc9b381a06193d27cf2fb7c2fb608a.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-04-29</div><div class="title">微信支付对接</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div id="twikoo-wrap"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="card-info-avatar is-center"><img class="avatar-img" src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@6b5e7ef72be1c8973d94e5a9c49accbf775ad820/2021/02/01/c485da031fe0e464d04eaba8a66c4a8f.png" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/><div class="author-info__name">小李博客</div><div class="author-info__description">越努力，越幸运！</div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">210</div></a></div><div class="card-info-data-item is-center"><a href="/tags/"><div class="headline">标签</div><div class="length-num">38</div></a></div><div class="card-info-data-item is-center"><a href="/categories/"><div class="headline">分类</div><div class="length-num">56</div></a></div></div><a class="button--animated" id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/xiaoliblog"><i class="fab fa-github"></i><span>博主的GitHub首页</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://gitee.com/xiaoliblog" target="_blank" title="Gitee"><i class="iconfont icon-gitee card_icon_gitee"></i></a><a class="social-icon" href="https://space.bilibili.com/390969485" target="_blank" title="BiliBili"><i class="iconfont icon-bilibili card_icon_bilibili"></i></a><a class="social-icon" href="http://wpa.qq.com/msgrd?v=3&amp;uin=2312057536&amp;site=CSDN&amp;menu=yes" target="_blank" title="QQ"><i class="iconfont icon-qq card_icon_qq"></i></a><a class="social-icon" href="https://github.com/xiaoliblog" target="_blank" title="GitHub"><i class="iconfont icon-git card_icon_git"></i></a><a class="social-icon" href="https://blog.csdn.net/qq_43266250?spm=1010.2135.3001.5113" target="_blank" title="CSDN"><i class="iconfont icon-csdn card_icon_csdn"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn card-announcement-animation"></i><span>公告</span></div><div class="announcement_content">正在考研备考中💦</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#%E7%94%B5%E5%AD%90%E9%82%AE%E4%BB%B6%E7%9A%84%E6%8E%A5%E5%8F%91%E8%BF%87%E7%A8%8B"><span class="toc-number">1.</span> <span class="toc-text">电子邮件的接发过程</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E9%82%AE%E4%BB%B6%E6%9C%8D%E5%8A%A1%E5%99%A8"><span class="toc-number">1.1.</span> <span class="toc-text">邮件服务器</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%94%B5%E5%AD%90%E9%82%AE%E7%AE%B1"><span class="toc-number">1.2.</span> <span class="toc-text">电子邮箱</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E9%82%AE%E4%BB%B6%E5%AE%A2%E6%88%B7%E7%AB%AF%E8%BD%AF%E4%BB%B6"><span class="toc-number">1.3.</span> <span class="toc-text">邮件客户端软件</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E9%82%AE%E4%BB%B6%E4%BC%A0%E8%BE%93%E5%8D%8F%E8%AE%AE"><span class="toc-number">1.4.</span> <span class="toc-text">邮件传输协议</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#JavaMail"><span class="toc-number">2.</span> <span class="toc-text">JavaMail</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#JavaMail%E4%BB%8B%E7%BB%8D"><span class="toc-number">2.1.</span> <span class="toc-text">JavaMail介绍</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#JavaMail-API"><span class="toc-number">2.2.</span> <span class="toc-text">JavaMail API</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%BC%80%E5%90%AF%E6%9C%8D%E5%8A%A1%E5%8F%8A%E6%8E%88%E6%9D%83%E7%A0%81"><span class="toc-number">2.3.</span> <span class="toc-text">开启服务及授权码</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E7%AE%80%E5%8D%95%E9%82%AE%E4%BB%B6"><span class="toc-number">3.</span> <span class="toc-text">简单邮件</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%8F%91%E9%80%81%E6%AD%A5%E9%AA%A4"><span class="toc-number">3.1.</span> <span class="toc-text">发送步骤</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%BC%96%E7%A0%81%E5%AE%9E%E7%8E%B0"><span class="toc-number">3.2.</span> <span class="toc-text">编码实现</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%A4%8D%E6%9D%82%E9%82%AE%E4%BB%B6"><span class="toc-number">4.</span> <span class="toc-text">复杂邮件</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#MIME"><span class="toc-number">4.1.</span> <span class="toc-text">MIME</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%8F%91%E9%80%81%E5%9B%BE%E7%89%87"><span class="toc-number">4.2.</span> <span class="toc-text">发送图片</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%8F%91%E9%80%81%E5%9B%BE%E7%89%87%E5%92%8C%E9%99%84%E4%BB%B6"><span class="toc-number">4.3.</span> <span class="toc-text">发送图片和附件</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E6%8E%A5%E6%94%B6%E9%82%AE%E4%BB%B6"><span class="toc-number">5.</span> <span class="toc-text">接收邮件</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E6%B3%A8%E5%86%8C%E9%82%AE%E4%BB%B6%E5%AE%9E%E4%BE%8B"><span class="toc-number">6.</span> <span class="toc-text">注册邮件实例</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%89%8D%E7%AB%AF%E7%95%8C%E9%9D%A2"><span class="toc-number">6.1.</span> <span class="toc-text">前端界面</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%AE%9E%E4%BD%93%E7%B1%BB"><span class="toc-number">6.2.</span> <span class="toc-text">实体类</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Servlet"><span class="toc-number">6.3.</span> <span class="toc-text">Servlet</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E9%82%AE%E4%BB%B6%E5%8F%91%E9%80%81%E5%B7%A5%E5%85%B7%E7%B1%BB"><span class="toc-number">6.4.</span> <span class="toc-text">邮件发送工具类</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%BF%90%E8%A1%8C%E7%BB%93%E6%9E%9C"><span class="toc-number">6.5.</span> <span class="toc-text">运行结果</span></a></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/page/project01.html" title="前端实例🥳响应式网站首页"><img src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@c19917500ab083c77c7613263ba7ee74d5a08ae6/2021/04/30/469f30b141d73fa0fc4c962662d5813f.png" onerror="this.onerror=null;this.src='https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/11/19/bd16b394f7359083b1f6072a67e3f968.png'" alt="前端实例🥳响应式网站首页"/></a><div class="content"><a class="title" href="/page/project01.html" title="前端实例🥳响应式网站首页">前端实例🥳响应式网站首页</a><time datetime="2021-04-30T11:50:53.094Z" title="发表于 2021-04-30 19:50:53">2021-04-30</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/page/WeChatpay.html" title="微信支付对接"><img src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@f2f670b92ea149650ffa7834354fc90284f2f44a/2021/04/29/5bdc9b381a06193d27cf2fb7c2fb608a.png" onerror="this.onerror=null;this.src='https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/11/19/bd16b394f7359083b1f6072a67e3f968.png'" alt="微信支付对接"/></a><div class="content"><a class="title" href="/page/WeChatpay.html" title="微信支付对接">微信支付对接</a><time datetime="2021-04-29T12:20:48.070Z" title="发表于 2021-04-29 20:20:48">2021-04-29</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/page/Alipay.html" title="支付宝支付对接"><img src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@61a9b6a6e09e4bda38bb08e3104b717885beaee5/2021/04/29/c3fa51f9cf14e90d9e5a7aa8814dd041.png" onerror="this.onerror=null;this.src='https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/11/19/bd16b394f7359083b1f6072a67e3f968.png'" alt="支付宝支付对接"/></a><div class="content"><a class="title" href="/page/Alipay.html" title="支付宝支付对接">支付宝支付对接</a><time datetime="2021-04-27T16:00:00.000Z" title="发表于 2021-04-28 00:00:00">2021-04-28</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/page/Vuejs11.html" title="Vue.js前端框架🎯Pagination+PageHelper实现分页"><img src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@61bf4245f6d84d2d0f66d163b89c916788cc1845/2021/04/13/ec6b232f8fe5a840e4bd8c3eabcf49b2.png" onerror="this.onerror=null;this.src='https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/11/19/bd16b394f7359083b1f6072a67e3f968.png'" alt="Vue.js前端框架🎯Pagination+PageHelper实现分页"/></a><div class="content"><a class="title" href="/page/Vuejs11.html" title="Vue.js前端框架🎯Pagination+PageHelper实现分页">Vue.js前端框架🎯Pagination+PageHelper实现分页</a><time datetime="2021-04-26T14:48:39.701Z" title="发表于 2021-04-26 22:48:39">2021-04-26</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/page/Vuejs10.html" title="Vue.js前端框架🎯Vue-Element-admin模版"><img src="https://cdn.jsdelivr.net/gh/xiaoliblog/image@61bf4245f6d84d2d0f66d163b89c916788cc1845/2021/04/13/ec6b232f8fe5a840e4bd8c3eabcf49b2.png" onerror="this.onerror=null;this.src='https://cdn.jsdelivr.net/gh/lzyblog/image@main/2020/11/19/bd16b394f7359083b1f6072a67e3f968.png'" alt="Vue.js前端框架🎯Vue-Element-admin模版"/></a><div class="content"><a class="title" href="/page/Vuejs10.html" title="Vue.js前端框架🎯Vue-Element-admin模版">Vue.js前端框架🎯Vue-Element-admin模版</a><time datetime="2021-04-19T16:00:00.000Z" title="发表于 2021-04-20 00:00:00">2021-04-20</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2021 By 小李博客</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">🎯Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">🎉Butterfly</a></div><div class="footer_custom_text"><span><a style="margin-inline:5px" target="_blank" href="https://hexo.io/"><img src="https://img.shields.io/badge/Frame-Hexo-blue?style=flat&logo=hexo" title="博客框架为Hexo"></a><a style="margin-inline:5px" target="_blank" href="https://butterfly.js.org/"><img src="https://img.shields.io/badge/Theme-Butterfly-6513df?style=flat&logo=bitdefender" title="主题采用butterfly"></a><a style="margin-inline:5px" target="_blank" href="https://www.jsdelivr.com/"><img src="https://img.shields.io/badge/CDN-jsDelivr-orange?style=flat&logo=jsDelivr" title="本站使用JsDelivr为静态资源提供CDN加速"></a><a style="margin-inline:5px" target="_blank" href="https://vercel.com/ "><img src="https://img.shields.io/badge/Hosted-Vercel-brightgreen?style=flat&logo=Vercel" title="本站采用双线部署，默认线路托管于Vercel"></a><a style="margin-inline:5px" target="_blank" href="https://coding.net/ "><img src="https://img.shields.io/badge/Hosted-Coding-0cedbe?style=flat&logo=Codio" title="本站采用双线部署，联通线路托管于Coding"></a><a style="margin-inline:5px" target="_blank" href="https://github.com/"><img src="https://img.shields.io/badge/Source-Github-d021d6?style=flat&logo=GitHub" title="本站项目由Gtihub托管"></a><a style="margin-inline:5px" target="_blank" href="http://creativecommons.org/licenses/by-nc-sa/4.0/"><img src="https://img.shields.io/badge/Copyright-BY--NC--SA%204.0-d42328?style=flat&logo=Claris" title="本站采用知识共享署名-非商业性使用-相同方式共享4.0国际许可协议进行许可"></a></span></div><div class="icp"><a target="_blank" rel="noopener" href="https://beian.miit.gov.cn/"><img class="icp-icon" src="/img/icp.png" alt="ICP"/><span>湘ICP备2021002541号</span></a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="font-plus" type="button" title="放大字体"><i class="fas fa-plus"></i></button><button id="font-minus" type="button" title="缩小字体"><i class="fas fa-minus"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="chat_btn" type="button" title="rightside.chat_btn"><i class="fas fa-sms"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="algolia-search"><div class="search-dialog"><div class="search-dialog__title" id="algolia-search-title">Algolia</div><div id="algolia-input-panel"><div id="algolia-search-input"></div></div><hr/><div id="algolia-search-results"><div id="algolia-hits"></div><div id="algolia-pagination"></div><div id="algolia-stats"></div></div><span class="search-close-button"><i class="fas fa-times"></i></span></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="https://cdn.jsdelivr.net/npm/vue@2.6.11"></script><script src="/js/main.js"></script><script defer src="/js/tw_cn.js"></script><script defer src="https://cdn.jsdelivr.net/npm/medium-zoom/dist/medium-zoom.min.js"></script><script src="https://cdn.jsdelivr.net/npm/instant.page/instantpage.min.js" type="module" defer></script><script defer src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><script defer src="/js/search/algolia.js"></script><div class="js-pjax"><script>if (!window.MathJax) {
  window.MathJax = {
    loader: {
      source: {
        '[tex]/amsCd': '[tex]/amscd'
      }
    },
    tex: {
      inlineMath: [ ['$','$'], ["\\(","\\)"]],
      tags: 'ams'
    },
    options: {
      renderActions: {
        findScript: [10, doc => {
          for (const node of document.querySelectorAll('script[type^="math/tex"]')) {
            const display = !!node.type.match(/; *mode=display/)
            const math = new doc.options.MathItem(node.textContent, doc.inputJax[0], display)
            const text = document.createTextNode('')
            node.parentNode.replaceChild(text, node)
            math.start = {node: text, delim: '', n: 0}
            math.end = {node: text, delim: '', n: 0}
            doc.math.push(math)
          }
        }, ''],
        addClass: [200,() => {
          document.querySelectorAll('mjx-container:not([display=\'true\']').forEach( node => {
            const target = node.parentNode
            if (!target.classList.contains('has-jax')) {
              target.classList.add('mathjax-overflow')
            }
          })
        }, '', false]
      }
    }
  }
  
  const script = document.createElement('script')
  script.src = 'https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js'
  script.id = 'MathJax-script'
  script.async = true
  document.head.appendChild(script)
} else {
  MathJax.startup.document.state(0)
  MathJax.texReset()
  MathJax.typeset()
}</script><script>if (document.getElementsByClassName('mermaid').length) {
  if (window.mermaidJsLoad) mermaid.init()
  else {
    getScript('https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js').then(() => {
      window.mermaidJsLoad = true
      mermaid.initialize({
        theme: 'default',
      })
      false && mermaid.init()
    })
  }
}</script><script>(()=>{
  const $countDom = document.getElementById('twikoo-count')
  const init = () => {
    twikoo.init(Object.assign({
      el: '#twikoo-wrap',
      envId: 'xiaoliblog-8gj3j5045d5b0896',
      region: ''
    }, null))
  }

  const getCount = () => {
    twikoo.getCommentsCount({
      envId: 'xiaoliblog-8gj3j5045d5b0896',
      region: '',
      urls: [window.location.pathname],
      includeReply: false
    }).then(function (res) {
      $countDom.innerText = res[0].count
    }).catch(function (err) {
      console.error(err);
    });
  }

  const loadTwikoo = (bool = false) => {
    if (typeof twikoo === 'object') {
      init()
      bool && $countDom && setTimeout(getCount,0)
    } else {
      getScript('https://cdn.jsdelivr.net/npm/twikoo@1.3.0/dist/twikoo.all.min.js').then(()=> {
        init()
        bool && $countDom && setTimeout(getCount,0)
      })
    }
  }

  if ('Twikoo' === 'Twikoo' || !true) {
    if (true) btf.loadComment(document.getElementById('twikoo-wrap'), loadTwikoo)
    else loadTwikoo(true)
  } else {
    window.loadOtherComment = () => {
      loadTwikoo()
    }
  }
})()</script></div><script defer src="//lib.baomitu.com/jquery/3.5.1/jquery.min.js"></script><script defer src="https://myhkw.cn/api/player/160561664166" id="myhk" key="160561664166" m="1"></script><div><canvas id="snow" style="position:fixed;top:0;left:0;width:100%;height:100%;z-index:99999;pointer-events:none"></canvas></div><script>const notMobile = (!(navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i)));</script><scrip async type="text/javascript" src="https://cdn.jsdelivr.net/gh/Candinya/Kratos-Rebirth@latest/source/js/snow.min.js"></scrip><scrip defer src="https://cdn.jsdelivr.net/npm/hexo-theme-volantis@latest/source/js/issues.min.js"></scrip><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><script>var gitcalendar = new Vue({
  el: '#gitcalendar',
  data: {
    simplemode: true, 
    user: 'xiaoliblog',
    fixed: 'fixed',
    px: 'px',
    x: '',
    y: '',
    span1: '',
    span2: '',
    month: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
    monthchange: [],
    oneyearbeforeday: '',
    thisday: '',
    amonthago: '',
    aweekago: '',
    weekdatacore: 0,
    datacore: 0,
    total: 0,
    datadate: '',
    data: [],
    positionplusdata: [],
    firstweek: [],
    lastweek: [],
    beforeweek: [],
    thisweekdatacore: 0,
    mounthbeforeday: 0,
    mounthfirstindex: 0,
    crispedges: 'crispedges',
    thisdayindex: 0,
    amonthagoindex: 0,
    amonthagoweek: [],
    firstdate: [],
    first2date: [],
    montharrbefore: [],
    monthindex: 0,
    color: ['#ebedf0', '#f1f8ff', '#dbedff', '#c8e1ff', '#79b8ff', '#2188ff', '#0366d6', '#005cc5', '#044289', '#032f62', '#05264c']
  },
  methods: {
    selectStyle(data, event) {
      document.querySelector('.angle-wrapper').style.display = 'block'
      this.span1 = data.date;
      this.span2 = data.count;
      this.x = event.clientX - 100;
      this.y = event.clientY - 60
    },
    outStyle() {
      document.querySelector('.angle-wrapper').style.display = 'none'
    },
    thiscolor(x) {
      if (x === 0) {
        let i = parseInt(x / 2);
        return this.color[0]
      } else if (x < 2) {
        return this.color[1]
      } else if (x < 20) {
        let i = parseInt(x / 2);
        return this.color[i]
      } else {
        return this.color[9]
      }
    },
  }
});
var apiurl = 'python-github-calendar-api-ruby.vercel.app' ? 'https://python-github-calendar-api-ruby.vercel.app/api?' : 'https://githubapi.ryanchristian.dev/user/'
var githubapiurl = apiurl + gitcalendar.user;
//canvas绘图
function responsiveChart() {
  let c = document.getElementById("gitcanvas");
  if (c) {
    let cmessage = document.getElementById("gitmessage");
    let ctx = c.getContext("2d");
    c.width = document.getElementById("gitcalendarcanvasbox").offsetWidth;
    let linemaxwitdh = 0.96 * c.width / gitcalendar.data.length;
    c.height = 9 * linemaxwitdh;
    let lineminwitdh = 0.8 * linemaxwitdh;
    let setposition = {
      x: 0.02 * c.width,
      y: 0.025 * c.width
    };
    for (let week in gitcalendar.data) {
      weekdata = gitcalendar.data[week];
      for (let day in weekdata) {
        let dataitem = {
          date: "",
          count: "",
          x: 0,
          y: 0
        };
        gitcalendar.positionplusdata.push(dataitem);
        ctx.fillStyle = gitcalendar.thiscolor(weekdata[day].count);
        setposition.y = Math.round(setposition.y * 100) / 100;
        dataitem.date = weekdata[day].date;
        dataitem.count = weekdata[day].count;
        dataitem.x = setposition.x;
        dataitem.y = setposition.y;
        ctx.fillRect(setposition.x, setposition.y, lineminwitdh, lineminwitdh);
        setposition.y = setposition.y + linemaxwitdh
      };
      setposition.y = 0.025 * c.width;
      setposition.x = setposition.x + linemaxwitdh
    };
    ctx.font = "600  Arial";
    ctx.fillStyle = '#aaa';
    ctx.fillText("日", 0, 1.9 * linemaxwitdh);
    ctx.fillText("二", 0, 3.9 * linemaxwitdh);
    ctx.fillText("四", 0, 5.9 * linemaxwitdh);
    ctx.fillText("六", 0, 7.9 * linemaxwitdh);
    let monthindexlist = c.width / 24;
    for (let index in gitcalendar.monthchange) {
      ctx.fillText(gitcalendar.monthchange[index], monthindexlist, 0.7 * linemaxwitdh);
      monthindexlist = monthindexlist + c.width / 12
    };
    cmessage.onmousemove = function(event) {
      document.querySelector('.angle-wrapper').style.display = 'none'
    };
    c.onmousemove = function(event) {
      document.querySelector('.angle-wrapper').style.display = 'none'
      getMousePos(c, event);
    };

    function getMousePos(canvas, event) {
      var rect = canvas.getBoundingClientRect();
      var x = event.clientX - rect.left * (canvas.width / rect.width);
      var y = event.clientY - rect.top * (canvas.height / rect.height);
      //console.log("x:"+x+",y:"+y);
      for (let item of gitcalendar.positionplusdata) {
        let lenthx = x - item.x;
        let lenthy = y - item.y;
        //console.log(lenthx,lenthy);
        if (0 < lenthx && lenthx < lineminwitdh) {
          if (0 < lenthy && lenthy < lineminwitdh) {
            //console.log(item.date,item.count)
            document.querySelector('.angle-wrapper').style.display = 'block'
            gitcalendar.span1 = item.date;
            gitcalendar.span2 = item.count;
            gitcalendar.x = event.clientX - 100;
            gitcalendar.y = event.clientY - 60
          }
        }
        //if(0< x - item.x <lineminwitdh&&0< y - item.y <lineminwitdh){
        //console.log(item.count,item.date);
        //}
      }
    }
  }
}
//数据统计算法
function addlastmonth() {
  if (gitcalendar.thisdayindex === 0) {
    thisweekcore(52);
    thisweekcore(51);
    thisweekcore(50);
    thisweekcore(49);
    thisweekcore(48);
    gitcalendar.thisweekdatacore += gitcalendar.firstdate[6].count;
    gitcalendar.amonthago = gitcalendar.firstdate[6].date
  } else {
    thisweekcore(52);
    thisweekcore(51);
    thisweekcore(50);
    thisweekcore(49);
    thisweek2core();
    gitcalendar.amonthago = gitcalendar.first2date[gitcalendar.thisdayindex - 1].date
  }
};

function thisweek2core() {
  for (let i = gitcalendar.thisdayindex - 1; i < gitcalendar.first2date.length; i++) {
    gitcalendar.thisweekdatacore += gitcalendar.first2date[i].count
  }
};

function thisweekcore(index) {
  for (let item of gitcalendar.data[index]) {
    gitcalendar.thisweekdatacore += item.count
  }
};

function addlastweek() {
  for (let item of gitcalendar.lastweek) {
    gitcalendar.weekdatacore += item.count
  }
};

function addbeforeweek() {
  for (let i = gitcalendar.thisdayindex; i < gitcalendar.beforeweek.length; i++) {
    gitcalendar.weekdatacore += gitcalendar.beforeweek[i].count
  }
};

function addweek(data) {
  if (gitcalendar.thisdayindex === 6) {
    gitcalendar.aweekago = gitcalendar.lastweek[0].date;
    addlastweek()
  } else {
    lastweek = data.contributions[51];
    gitcalendar.aweekago = lastweek[gitcalendar.thisdayindex + 1].date;
    addlastweek();
    addbeforeweek()
  }
}

fetch(githubapiurl)
  .then(data => data.json())
  .then(data => {
    gitcalendar.data = data.contributions;
    gitcalendar.total = data.total;
    gitcalendar.first2date = gitcalendar.data[48];
    gitcalendar.firstdate = gitcalendar.data[47];
    gitcalendar.firstweek = data.contributions[0];
    gitcalendar.lastweek = data.contributions[52];
    gitcalendar.beforeweek = data.contributions[51];
    gitcalendar.thisdayindex = gitcalendar.lastweek.length - 1;
    gitcalendar.thisday = gitcalendar.lastweek[gitcalendar.thisdayindex].date;
    gitcalendar.oneyearbeforeday = gitcalendar.firstweek[0].date;
    gitcalendar.monthindex = gitcalendar.thisday.substring(5, 7) * 1;
    gitcalendar.montharrbefore = gitcalendar.month.splice(gitcalendar.monthindex, 12 - gitcalendar.monthindex);
    gitcalendar.monthchange = gitcalendar.montharrbefore.concat(gitcalendar.month);
    addweek(data);
    addlastmonth();
    responsiveChart();
  })
  .catch(function(error) {
    console.log(error);
  });

//手机版更换为svg绘制
if (document.getElementById("gitcalendarcanvasbox").offsetWidth < 500) {
  gitcalendar.simplemode = false
}

//当改变窗口大小时重新绘制canvas
window.onresize = function() {
  if (gitcalendar.simplemode) responsiveChart()
}

//解决滚动滑轮时出现的标签显示
window.onscroll = function() {
  if (document.querySelector('.angle-wrapper')) {
    document.querySelector('.angle-wrapper').style.display = 'none'
  }
};</script></div><script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"log":false,"model":{"jsonPath":"/live2dw/assets/hijiki.model.json"},"display":{"position":"right","width":150,"height":300},"mobile":{"show":true},"react":{"opacity":0.7}});</script></body></html>